<template>
  <BasicDrawer v-bind="$attrs" width="30%" showFooter @register="registerDrawer" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { message } from "ant-design-vue";
  import { BasicDrawer, useDrawerInner, BasicForm, useForm } from '@gui-pkg/antdcomponents';
  import { accountFormSchema } from './account.data';
  // import { getDeptList } from '@/api/system/account';
  import { addUser, editUser } from '@/api/system/account';

  const isUpdate = ref(true);
  const rowId = ref('');
  const emit = defineEmits(['success', 'register']);

  const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: accountFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    console.log(data.record, 'data.recorddata.recorddata.record');

    if (unref(isUpdate)) {
      rowId.value = data.record.userId;
      const roleids = data.record?.roles;
      setFieldsValue({
        ...data.record,
        roleIds: roleids
      });
    }

    /*const treeData = await getDeptList();
    updateSchema([
      {
        field: 'pwd',
        show: !unref(isUpdate),
      },
      {
        field: 'dept',
        componentProps: { treeData },
      },
    ]);*/
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增账号' : '编辑账号'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      // TODO custom api
      console.log(values, '向后台提交菜单数据');
      // 向后台提交菜单数据
      if (unref(isUpdate)) {
        await editUser({...values, userId: rowId.value});
        message.success('编辑成功');
      } else {
        await addUser(values);
        message.success('新增成功');
      }
      closeDrawer();
      emit('success', { isUpdate: unref(isUpdate), values: { ...values, userId: rowId.value } });
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>

<style lang="less" rel="stylesheet/less" scoped>

</style>
